package com.domor.system.service;

import com.domor.system.domain.SysMsg;
import com.domor.system.domain.SysNotice;
import com.domor.system.domain.SysUser;
import com.domor.system.mapper.SysMsgMapper;
import com.domor.system.mapper.SysNoticeMapper;
import com.domor.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <h3>公告 服务层</h3>
 * @author liyuyang
 * @date 2020/5/11
 **/
@Service
public class SysNoticeService {

    @Autowired
    private SysNoticeMapper noticeMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysMsgMapper msgMapper;

    /**
     * 查询公告信息
     *
     * @param noticeId 公告ID
     * @return 公告信息
     */
    public SysNotice selectNoticeById(Integer noticeId) {
        return noticeMapper.selectNoticeById(noticeId);
    }

    /**
     * 查询公告列表
     *
     * @param notice 公告信息
     * @return 公告集合
     */
    public List<SysNotice> selectNoticeList(SysNotice notice) {
        return noticeMapper.selectNoticeList(notice);
    }

    /**
     * 新增公告
     *
     * @param notice 公告信息
     * @return 结果
     */
    @Transactional
    public int insertNotice(SysNotice notice, SysUser user) throws Exception{
        // 插入公告表
        int row = noticeMapper.insertNotice(notice);
        // 推送消息
        List<String> users = userMapper.selectAllUser();
        String type = notice.getNoticeType() == 1 ? "通知" : "公告";
        String content = "【"+user.getUserName()+"】"+"给您发送了一条"+type+"【"+notice.getNoticeTitle()+"】";
        List<SysMsg> msgs = new ArrayList<>();
        for (String userId : users) {
            SysMsg sysMsg = new SysMsg(userId, "notice", content, notice.getNoticeId(), notice.getCreateBy());
            msgs.add(sysMsg);
            WebSocketServer.send(sysMsg);
        }
        // 批量插入消息表
        msgMapper.batchInsert(msgs);
        return row;
    }

    /**
     * 修改公告
     *
     * @param notice 公告信息
     * @return 结果
     */
    public int updateNotice(SysNotice notice) {
        return noticeMapper.updateNotice(notice);
    }

    /**
     * 删除公告对象
     *
     * @param noticeId 需要删除的数据ID
     * @return 结果
     */
    public int deleteNoticeById(Integer noticeId) {
        return noticeMapper.deleteNoticeById(noticeId);
    }

}
